import { getValueByKey } from 'csui'
import { useTableColumnProps } from '/@/hooks/table-column/props'

/**
 * 使用table formatter
 * @param prop column.prop
 * @param label column.label
 * @param formatter column.formatter
 * @param options tableColumn的其他属性
 * @returns tableColumn props
 */
export function useTableColumnFormatter<
  T extends Record<string, any>,
  P extends keyof T
>(
  prop: P,
  label: string,
  formatter: TableColumnProps<T>['formatter'],
  options: UseTableColumnProps<any, T, P> = {}
) {
  return useTableColumnProps<T, P>(prop, label, {
    ...options,
    formatter
  })
}

/**
 * 使用table formatter 生成多行数据
 * @param prop column.prop
 * @param label column.label
 * @param options tableColumn的其他属性
 * @param map 映射数据源
 * @returns tableColumn props
 */
export function useTableColumnMultipleRows<
  T extends Record<string, any>,
  P extends `${keyof T & string}.${string}`
>(
  prop: P,
  label: string,
  options: UseTableColumnProps<any, T, P> = {},
  map?: Record<string, any>
) {
  return useTableColumnProps<T, P>(prop, label, {
    ...options,
    formatter: row => {
      const [currentProp, ...rowProps] = prop.split('.')
      const rowProp = rowProps.join('.')
      const cellValue = row[currentProp] || []
      return (
        <>
          {cellValue.map((item: any) => (
            <div class="table-column-multiple-rows">
              {map ?
                getValueByKey(map, getValueByKey(item, rowProp)) :
                getValueByKey(item, rowProp)}
            </div>
          ))}
        </>
      )
    }
  })
}
